﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Serialization;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Phone.Info;
using System.Threading;
using Microsoft.Phone.Shell;
using ACTT_WP7.Resources;

namespace ACTT_WP7
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public static City current_city;
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);


            try
            {
                var occ = LoadUtilizations() + 1;
                new Thread(new ThreadStart(() =>
                {
                    getHTML(GetUtilizationUrl(occ),
                        (s) =>
                        {
                            DeleteUtilizations();
                        },
                        () =>
                        {
                            SaveUtilizations(occ);
                        });
                })).Start();
            }
            catch { }


            ApplicationBar.Buttons.Clear();
            ApplicationBarIconButton credits = new ApplicationBarIconButton() { Text = Strings.Credits, IsEnabled = true };

            if (App.CurrentTheme == App.Theme.Dark)
                credits.IconUri = new Uri("\\Images\\dark\\appbar.questionmark.rest.png", UriKind.Relative);
            else
                credits.IconUri = new Uri("\\Images\\light\\appbar.questionmark.rest.png", UriKind.Relative);
            credits.Click += OpenCredits_Button_Click;
            ApplicationBar.Buttons.Add(credits);


            ApplicationBarIconButton settings = new ApplicationBarIconButton() { Text = Strings.Reload, IsEnabled = true };

            if (App.CurrentTheme == App.Theme.Dark)
                settings.IconUri = new Uri("\\Images\\dark\\appbar.feature.settings.rest.png", UriKind.Relative);
            else
                settings.IconUri = new Uri("\\Images\\light\\appbar.feature.settings.rest.png", UriKind.Relative);
            settings.Click += Reload_Button_Click;
            ApplicationBar.Buttons.Add(settings);

            LoadFile();
            ReloadData();
        }
        private void Reload_Button_Click(object sender, EventArgs e)
        {

            new Thread(new ThreadStart(() =>
            {
                getHTML("http://fboscari.altervista.org/ACTT/treviso.xml",
                    (s) =>
                    {
                        try
                        {
                            
                            StringReader reader = new StringReader(s);
                            XmlSerializer serializer = new XmlSerializer(typeof(City));
                            current_city = serializer.Deserialize(reader) as City;
                            SaveSavedOptions(current_city);
                            Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show(Strings.UpdateCompleted);
                                ReloadData();
                            });
                        }
                        catch (Exception ex)
                        {
                            ex.ToString();


                            Dispatcher.BeginInvoke(() =>
                            {
                                MessageBox.Show(Strings.ConnectionError);
                                ReloadData();
                            });
                        }
                    },
                    () =>
                    {

                        Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show(Strings.ConnectionError);
                            ReloadData();
                        });
                    });
            })).Start();

        }
        private void OpenCredits_Button_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/CreditsPage.xaml", UriKind.Relative));
        }
        // Handle selection changed on ListBox
        private void MainListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // If selected index is -1 (no selection) do nothing
            if (MainListBox.SelectedIndex == -1)
                return;

            // Navigate to the new page

            App.ViewModel.StopsItems.Clear();

            NavigationService.Navigate(new Uri("/DetailsPage.xaml?selectedItem=" + MainListBox.SelectedIndex, UriKind.Relative));

            // Reset selected index to -1 (no selection)
            MainListBox.SelectedIndex = -1;
        }

        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            Microsoft.Advertising.Mobile.UI.AdControl.TestMode = false;
            if (!App.ViewModel.IsDataLoaded)
            {
                App.ViewModel.LoadData();
            }

        }
        public void ReloadData()
        {

            /*if (current_city == null)
            {
                current_city = new City()
                {
                    Name = "Treviso",
                    ValidFrom = "01/06/2011",
                    ValidTo = "15/09/2011",
                    Lines = new List<Line>(){
                    new Line(){Name="1 - Feriale", Stops=new List<String>(){
                        "Note",
                        "Ospedale",
                        "Stazione FS"},
                        Trips = new List<String>(){
                                ";5:00;5:10",
                                "*;6:00;6:20",
                                ";7:10;7:20"
                        }
                    },
                    new Line(){Name="1 - Festivo", Stops=new List<String>(){
                        "Note","a","b"},
                        Trips=new List<String>(){
                                ";10:00;c",
                                ";11:00;d"
                        }
                    }
                }
                };
            }*/
            if (current_city != null)
            {
                App.ViewModel.LinesItems.Clear();
                MainListBox.SelectedIndex = -1;
                for (int i = 0; i < current_city.Lines.Count; i++)
                {
                    var l = current_city.Lines[i];
                    App.ViewModel.LinesItems.Add(new LinesViewModel() { Label = l.Name, Line = l });
                }
            }
        }
        public void LoadFile()
        {
            try
            {
                using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using (var streamFile = appStorage.OpenFile("treviso.xml", FileMode.Open))
                    {

                        XmlSerializer serializer = new XmlSerializer(typeof(City));
                        using (var reader = new StreamReader(streamFile))
                            current_city = serializer.Deserialize(reader) as City;

                    }
                }
            }
            catch (Exception) { current_city = new City(); }
        }

        public static void SaveSavedOptions(City state)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("treviso.xml");
                using (var streamFile = appStorage.OpenFile("treviso.xml", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                //write_options_state(writer, entry);
                {
                    XmlSerializer serializer = new XmlSerializer(typeof(City));
                    serializer.Serialize(writer, state);
                }
            }
        }


        public static void getHTML(string query, string options, Action<string> callback, Action<string, string> callback2, Action error)
        {
            try
            {
                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(query);
                req.Method = "GET";
                req.BeginGetResponse(
                    (asyncResult) =>
                    {
                        try
                        {
                            HttpWebResponse objResponse = null;
                            StreamReader objs = null;

                            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;

                            objResponse = (HttpWebResponse)request.EndGetResponse(asyncResult);
                            objs = new StreamReader(objResponse.GetResponseStream());

                            var s = objs.ReadToEnd();
                            if (callback2 != null)
                                callback2(s, options);
                            else if (callback != null)
                                callback(s);

                            return;
                        }
                        catch (Exception)
                        {
                            error();
                        }
                    }
                    , req);
            }
            catch (Exception)
            {
                error();
            }
        }
        public static void getHTML(string query, Action<string> callback, Action error)
        {
            getHTML(query, "", callback, null, error);
        }


        public static void getHTML(string query, string options, Action<string, string> callback, Action error)
        {
            getHTML(query, options, null, callback, error);
        }
        #region utilizations
        public static string GetUtilizationUrl(int occ)
        {

            var s = "http://fboscari.altervista.org/submit_Utilizzi.php?name=" +
                "ACTT_WP7" +
                "&id=" +
                getID();
            if (occ >= 1)
                s += "&occ=" +
                    occ;
            return s;

        }
        public static string getID()
        {
            byte[] result = null;
            object uniqueId;
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
                result = (byte[])uniqueId;
            var s = "";
            for (int i = 0; i < result.Length; i++)
                s += result[i];
            return s;
        }


        private static Func<StreamReader, int> read_utilizations = reader =>
        {

            var s = reader.ReadToEnd();
            var occ = Int16.Parse(s);


            return occ;
        };


        private static Action<StreamWriter, int> write_utilizations = (writer, occ) =>
        {
            var s = "" + occ;

            writer.Write(s);
        };



        public static void SaveUtilizations(int utilizations)
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                appStorage.DeleteFile("utilizations.txt");
                using (var streamFile = appStorage.OpenFile("utilizations.txt", FileMode.OpenOrCreate))
                using (var writer = new StreamWriter(streamFile))
                    write_utilizations(writer, utilizations);
            }
        }



        public static void DeleteUtilizations()
        {
            var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
            appStorage.DeleteFile("utilizations.txt");
        }

        public static int LoadUtilizations()
        {
            using (var appStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var streamFile = appStorage.OpenFile("utilizations.txt", FileMode.OpenOrCreate))
                {
                    try
                    {
                        using (var reader = new StreamReader(streamFile))
                            return read_utilizations(reader);
                    }
                    catch (Exception)
                    {
                        appStorage.DeleteFile("utilizations.txt");
                        return 0;
                    }
                }


            }

        }
        #endregion utilizations

    }
}